package com.bitejiuyeke.job_publish.utils;

import com.bitejiuyeke.job_publish.enums.UploadFileTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @Author 比特就业课
 */
@Slf4j
@Component
public class FileUtils {

    @Value("${local-resource.upload.root-path}")
    private String uploadRootPath;
    @Value("${local-resource.upload.image-path}")
    private String imagePath;
    @Value("${local-resource.upload.file-path}")
    private String filePath;

    public String saveFile (MultipartFile file, UploadFileTypeEnum typeEnum) throws IOException {
        // 校验
        if (file == null || StringUtils.isEmpty(file.getOriginalFilename())) {
            throw new IllegalArgumentException("上传的文件不能为空");
        }
        if (typeEnum == null) {
            throw new IllegalArgumentException("上传类型不能为空");
        }
        // 校验路径分隔符
        if (!uploadRootPath.endsWith("/")) {
            uploadRootPath = uploadRootPath + "/";
        }
        if (!imagePath.endsWith("/")) {
            imagePath = imagePath + "/";
        }
        if (!filePath.endsWith("/")) {
            filePath = filePath + "/";
        }
        // 目录路径
        String dirPath = null;
        String targetPath = null;
        switch (typeEnum){
            case PIC -> {
                dirPath = uploadRootPath + imagePath;
                targetPath = imagePath;
            }
            case FILE -> {
                dirPath = uploadRootPath + filePath;
                targetPath = filePath;
            }
            default -> throw new IllegalArgumentException("路径不正确");
        }
        // 检查路径是否存在
        File dir = new File(dirPath);
        if (!dir.exists()) {
            // 目录不存在则创建
            dir.mkdirs(); // 连同子目录一同创建
        }
        // 获取上传文件的后缀
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        // 生成随机字符串防止图片重各
        fileName = UUIDUtils.UUID_36() + suffix;
        //
        if (!dirPath.endsWith("/")) {
            dirPath = dirPath + "/";
        }
        // 写入磁盘
        file.transferTo(new File(dirPath + fileName));
        // 文件相对路径
        String resultPath = targetPath + fileName;
        // 返回结果
        return resultPath;
    }
}
